package com.chucang.shucang.ttp.listener;

import com.chucang.shucang.common.base.constant.CommonConstant;
import com.chucang.shucang.common.base.constant.SecurityConstant;
import com.chucang.shucang.common.base.exception.FastException;
import com.chucang.shucang.common.base.utils.OpsUtil;
import com.chucang.shucang.common.base.utils.R;
import com.chucang.shucang.common.mq.constant.RabbitConstant;
import com.chucang.shucang.common.mq.to.TransferTO;
import com.chucang.shucang.ttp.feign.UserService;
import com.chucang.shucang.ttp.feign.vo.WalletDeductionVO;
import com.chucang.shucang.ttp.service.AliPayService;
import com.rabbitmq.client.Channel;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @author flitsneak
 * @email flitsneak@gmail.com
 * @date 2022/10/23 13:53
 * @description 支付宝提现
 */
@Slf4j
@Component
@RequiredArgsConstructor
@RabbitListener(queues = RabbitConstant.ALIPAY_WITHDRAW_QUEUE)
public class AliPayWithdrawListener {
    private final AliPayService aliPayService;
    private final UserService userService;

    @RabbitHandler
    public void aliPayWithdrawListener(TransferTO transferTO, Channel channel, Message message) throws IOException {
        log.info("用户：{}发起提现请求", transferTO.getUsername());
        try {
            //先扣钱包，再转账，很重要！！
            //修改账单状态
            String billSn = transferTO.getBillSn();
            userService.finishBill(billSn, SecurityConstant.FROM_IN);
            //扣减钱包金额
            WalletDeductionVO walletDeductionVO = new WalletDeductionVO();
            walletDeductionVO.setUserId(transferTO.getUserId());
            walletDeductionVO.setAmount(transferTO.getWithdrawAmount());
            R<String> r = userService.walletDeduction(walletDeductionVO, SecurityConstant.FROM_IN);
            OpsUtil.of(r)
                    .assertCode(CommonConstant.SUCCESS, e -> new FastException("钱包扣减失败！"));
            aliPayService.transferBill(transferTO);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);

        } catch (Exception e) {
            log.error("提现失败！");
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
        }
    }
}
